import logging
import jwt
from flask import request, jsonify, send_file, Blueprint, current_app
from models import db, User, ModelRecord
import os
from datetime import datetime, timedelta

main = Blueprint('main', __name__)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# JWT 密钥
JWT_SECRET_KEY = 'your_jwt_secret_key'  # 请使用强随机密钥


# 辅助函数：生成统一的响应格式
def make_response(code, data=None, message=None):
    return jsonify({
        "code": code,
        "data": data,
        "message": message
    })

#用户注册
@main.route('/user/register', methods=['POST'])
def user_register():
    try:
        data = request.json
        userAccount = data.get('userAccount')
        userPassword = data.get('userPassword')
        userName = data.get('userName',userAccount)
        userProfile = data.get('userProfile','该用户还没有简介')
        userRole = data.get('userRole', 'user')  # 默认角色为 'user'

        if not userAccount or not userPassword:
            return make_response(400, None, "User account and password are required")

        # 检查用户是否已存在
        existing_user = User.query.filter_by(userAccount=userAccount).first()
        if existing_user:
            return make_response(409, None, "User account already exists")


        new_user = User(
            userAccount=userAccount,
            userPassword=userPassword,
            userName=userName,
            userProfile=userProfile,
            userRole=userRole
        )

        db.session.add(new_user)
        db.session.commit()

        return make_response(201, {"id": new_user.id, "userAccount": new_user.userAccount}, "User registered successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")

# 获取用户列表
@main.route('/users', methods=['GET'])
def users_list():
    try:
        users = User.query.all()
        user_data = [{
            "id": user.id,
            "userAccount": user.userAccount,
            "userName": user.userName,
            "userProfile": user.userProfile,
            "userRole": user.userRole,
            "editTime": user.editTime.isoformat(),
            "createTime": user.createTime.isoformat(),
            "updateTime": user.updateTime.isoformat(),
            "isDelete": user.isDelete
        } for user in users]
        return make_response(200, user_data, "Users retrieved successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")

# 用户登录
@main.route('/user/login', methods=['POST'])
def user_login():
    try:
        data = request.json
        account = data.get('account')
        password = data.get('password')

        print(f"Account: {account}, Password: {password}")

        if not account or not password:
            return make_response(400, None, "Account and password are required")

        # 查询用户
        user = User.query.filter_by(userAccount=account).first()
        if not user:
            logger.warning(f"Login attempt failed for account: {account}")
            return make_response(401, None, "Invalid username or password")


        # 验证密码
        if user.userPassword != password:
            logger.warning(f"Login attempt failed for account: {account}")
            return make_response(401, None, "Invalid username or password")


        # 生成 JWT Token
        payload = {
            'user_id': user.id,
            'exp': datetime.utcnow() + timedelta(hours=1)  # Token 有效期为 1 小时
        }
        token = jwt.encode(payload, JWT_SECRET_KEY, algorithm='HS256')

        return make_response(200, {"token": token, "userInfo": {"id": user.id, "userName": user.userName}}, "Login successful")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")

# 用户登出
@main.route('/user/logout', methods=['POST'])
def user_logout():
    return make_response(200, None, "User logged out successfully")


# 获取用户信息
@main.route('/user/info', methods=['GET'])
def user_info():
    try:
        token = request.headers.get('Authorization')
        if not token:
            return make_response(401, None, "Unauthorized")

        # 解析 JWT Token
        try:
            payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            return make_response(401, None, "Token has expired")
        except jwt.InvalidTokenError:
            return make_response(401, None, "Invalid token")

        user_id = payload['user_id']
        user = User.query.get(user_id)
        if not user:
            return make_response(404, None, "User not found")

        # 获取用户的所有信息
        user_data = {
            "id": user.id,
            "userAccount": user.userAccount,
            "userName": user.userName,
            "userProfile": user.userProfile,
            "userRole": user.userRole,
            "editTime": user.editTime.isoformat(),
            "createTime": user.createTime.isoformat(),
            "updateTime": user.updateTime.isoformat(),
            "isDelete": user.isDelete
        }

        return make_response(200, user_data, "User info retrieved successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")

#用户更新信息
@main.route('/user/update', methods=['POST'])
def user_update():
    try:
        # 获取 JWT Token
        token = request.headers.get('Authorization')
        if not token:
            return make_response(401, None, "Unauthorized")

        # 解析 JWT Token
        try:
            payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            return make_response(401, None, "Token has expired")
        except jwt.InvalidTokenError:
            return make_response(401, None, "Invalid token")

        # 获取用户ID
        user_id = payload['user_id']
        user = User.query.get(user_id)
        if not user:
            return make_response(404, None, "User not found")

        # 获取更新数据
        data = request.json
        user.userName = data.get('userName', user.userName)
        user.userProfile = data.get('userProfile', user.userProfile)

        # 保存更新
        db.session.commit()

        # 返回更新后的用户信息
        updated_user_data = {
            "id": user.id,
            "userAccount": user.userAccount,
            "userName": user.userName,
            "userProfile": user.userProfile,
            "userRole": user.userRole
        }
        return make_response(200, updated_user_data, "User updated successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")


# 获取所有建模记录列表
@main.route('/model/records', methods=['GET'])
def model_records_list():
    try:
        records = ModelRecord.query.all()
        logger.info(f"Number of model records found: {len(records)}")

        if not records:
            return make_response(404, None, "No model records found")

        record_data = [
            {
                "id": record.id,
                "userId": record.userId,
                "imageUrl": record.imageUrl,
                "modelUrl": record.modelUrl,
                "createdAt": record.createTime.isoformat()
            } for record in records
        ]
        return make_response(200, record_data, "Get model records successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")

# 获取用户相关的建模记录
@main.route('/model/user/records', methods=['GET'])
def user_model_records():
    try:
        # 获取 JWT Token
        token = request.headers.get('Authorization')
        if not token:
            return make_response(401, None, "Unauthorized")

        # 解析 JWT Token
        try:
            payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            return make_response(401, None, "Token has expired")
        except jwt.InvalidTokenError:
            return make_response(401, None, "Invalid token")

        user_id = payload['user_id']
        user = User.query.get(user_id)
        if not user:
            return make_response(404, None, "User not found")

        # 查询用户相关的建模记录
        records = ModelRecord.query.filter_by(userId=user.id).all()
        if not records:
            return make_response(404, None, "No model records found for this user")

        record_data = [
            {
                "id": record.id,
                "userId": record.userId,
                "imageUrl": record.imageUrl,
                "modelUrl": record.modelUrl,
                "createdAt": record.createTime.isoformat()
            } for record in records
        ]
        return make_response(200, record_data, "Get user model records successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")


@main.route('/model/upload', methods=['POST'])
def model_upload():
    try:
        if 'image' not in request.files:
            return make_response(400, None, "No image part")
        image = request.files['image']
        if image.filename == '':
            return make_response(400, None, "No selected file")
        if image:
            # 获取 JWT Token
            token = request.headers.get('Authorization')
            if not token:
                return make_response(401, None, "Unauthorized")

            # 解析 JWT Token
            try:
                payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=['HS256'])
            except jwt.ExpiredSignatureError:
                return make_response(401, None, "Token has expired")
            except jwt.InvalidTokenError:
                return make_response(401, None, "Invalid token")

            user_id = payload['user_id']
            user = User.query.get(user_id)
            if not user:
                return make_response(404, None, "User not found")

            # 生成时间戳

            timestamp = datetime.now()
            timestamp_str = timestamp.strftime("%Y%m%d%H%M%S")

            # 创建输出目录
            output_base_dir = os.path.join("assets", f"{user.userAccount}_{user.id}_{timestamp_str}")
            preprocess_dir = os.path.join(output_base_dir, "preprocess")
            inference_dir = os.path.join(output_base_dir, "inference")
            output_dir = os.path.join(output_base_dir, "output")
            os.makedirs(preprocess_dir, exist_ok=True)
            os.makedirs(inference_dir, exist_ok=True)
            os.makedirs(output_dir, exist_ok=True)

            # 保存上传的图片（使用原始文件名）
            original_filename = image.filename
            image_path = os.path.join(preprocess_dir, original_filename)
            image.save(image_path)

            # 1. 推理
            from utils.export_inference import run_inference
            model_path = "utils/ckpt/resnet50_rnn__st3d.pth"  # 替换为实际的模型路径
            run_inference(image_path, inference_dir, model_path)

            # 2. 导出 PLY 文件
            from utils.export_3d_model import export_3d_model
            layout_path = os.path.join(inference_dir, f"{os.path.splitext(original_filename)[0]}.json")
            ply_path = os.path.join(output_dir, f"{os.path.splitext(original_filename)[0]}.ply")
            export_3d_model(image_path, layout_path, ply_path)

            # 3.保存建模记录到数据库
            image_url = f"/assets/{user.userAccount}_{user.id}_{timestamp_str}/preprocess/{original_filename}"
            model_url = f"/assets/{user.userAccount}_{user.id}_{timestamp_str}/output/{os.path.splitext(original_filename)[0]}.ply"
            new_record = ModelRecord(userId=user_id, imageUrl=image_url, modelUrl=model_url, createTime=timestamp)
            db.session.add(new_record)
            db.session.commit()

            return make_response(201, {"recordId": new_record.id,"imageUrl": image_url, "modelUrl": model_url}, "Model created successfully")

    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")


@main.route('/model/result/ply/<recordId>', methods=['GET'])
def model_get(recordId):
    try:
        # 根据 recordId 查询数据库
        record = ModelRecord.query.filter_by(id=recordId).first()
        if record:
            # 获取 PLY 文件路径（假设 modelUrl 是相对路径）
            ply_path = os.path.join(current_app.root_path, record.modelUrl.lstrip('/'))
            ply_path = os.path.normpath(ply_path)  # 规范化路径格式
            logger.info(f"PLY file path: {ply_path}")
            if os.path.exists(ply_path):
                # 返回 PLY 文件
                return send_file(ply_path, mimetype='application/octet-stream')
            else:
                logger.error(f"PLY file not found at path: {ply_path}")
                return make_response(404, None, "PLY file not found")
        return make_response(404, None, "Model record not found")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return make_response(500, None, "Internal server error")
